mergeInto(LibraryManager.library, {
    JSEvent_WebCodecs_VideoDecoder_init__sig: 'i',
    JSEvent_WebCodecs_VideoDecoder_init: function(){
        let self = this;
        self.frameCount = 0;

        const init = {
            output: (videoFrame) => {
                self.frameCount++;
                console.log("output frame: " + self.frameCount);
                videoFrame.close();
            },
            error: (e) => {
                console.log(e.message);
            },
        };

        const config = {
            codec: "avc1.640028"
        };

        let supported = VideoDecoder.isConfigSupported(config);
        if (supported) {
            console.log("avc supported");
            let decoder = new VideoDecoder(init);
            decoder.configure(config);

            console.log(decoder);

            if(self.decoderSet == null){
                self.decoderSet = {};
            }
            let index = 1;
            while(true){
                if(self.decoderSet[index] == null){
                    self.decoderSet[index] = decoder;
                    break;
                }
                index++;
            }
            return index;
        } else {
            console.log("avc not supported");
            return -1;
        }

        return -1;
    },


    JSEvent_WebCodecs_VideoDecoder_init__sig: 'iiiii',
    JSEvent_WebCodecs_VideoDecoder_decode: function(decoderIndex, buf, bufSize, pts){
        console.log("decoder bufSize: " + bufSize + "  pts: " + pts);
        let self = this;

        let jsData = new Uint8Array(HEAPU8.subarray(buf, buf + bufSize));
        let chunk = new EncodedVideoChunk({
            timestamp: pts,
            type: "delta",
            data: jsData
        });

        let decoder = self.decoderSet[decoderIndex];
        decoder.decode(chunk);

        console.log("decodeQueueSize: " + decoder.decodeQueueSize);

        return 0;
    },

    JSEvent_WebCodecs_VideoDecoder_flush__sig: 'ii',
    JSEvent_WebCodecs_VideoDecoder_flush: function(decoderIndex){
        let decoder = self.decoderSet[decoderIndex];
        decoder.flush()
        return 0;
    }
})